const path = require('path');
// const CopyWebpackPlugin = require('copy-webpack-plugin'); //最新版本copy-webpack-plugin插件暂不兼容，推荐v5.0.0

const resolve = dir => path.join(__dirname, dir);

const isBuild = process.env.NODE_ENV === 'production'; // 是否打包
const isProduction = process.env.VUE_APP_ENV === 'production'; // 是否生产环境

const Alias = {
  '@': 'src',
  '@assets': 'src/assets',
  '@components': 'src/components',
  '@static': 'src/static',
  '@pages': 'src/pages',
  '@store': 'src/store'
};

console.log(process.env.VUE_APP_ENV, process.env.NODE_ENV, isProduction);
console.log(process.env.UNI_OUTPUT_DIR, 'UNI_OUTPUT_DIR');

const manifestJsonObj = require('@dcloudio/uni-cli-shared/lib/manifest').getManifestJson();

// const platformOptions = manifestJsonObj[process.env.UNI_SUB_PLATFORM || process.env.UNI_PLATFORM] || {};
//
// const { manifestPlatformOptions } = require('@dcloudio/vue-cli-plugin-uni/lib/env');
// const { htmlPreprocessOptions } = require('@dcloudio/uni-cli-shared');

console.log(global.uniPlugin.options);

// if (process.UNI_MANIFEST) {
//   process.UNI_MANIFEST['mp-weixin']['projectname'] = '123123';
//   console.log(process.UNI_MANIFEST);
// }
// UNI_MANIFEST:

const rules = [
  {
    test: path.resolve(process.env.UNI_INPUT_DIR, 'pages.json'),
    use: [
      {
        loader: '@azm/webpack-pagoda-pages-loader'
      }
    ],
    type: 'javascript/auto'
  }
];

module.exports = {
  configureWebpack: {
    plugins: [
      // new webpack.ProvidePlugin({
      //     'localStorage': ['mp-storage', 'localStorage'],
      //     'window.localStorage': ['mp-storage', 'localStorage']
      // }),
      // new CopyWebpackPlugin([
      //   {
      //     from: path.join(__dirname, 'src'),
      //     to: path.join(
      //       __dirname,
      //       'dist',
      //       process.env.NODE_ENV === 'production' ? 'ddd' : 'dev',
      //       process.env.UNI_PLATFORM
      //     )
      //   }
      // ])
    ],
    module: {
      rules
    }
  },
  chainWebpack: config => {
    // 添加别名
    const alias = config.resolve.alias;
    Object.keys(Alias).forEach(key => alias.set(key, resolve(Alias[key])));

    config.plugin('define').tap(args => {
      args[0]['process.env'].VUE_APP_TEST = '"test"';
      return args;
    });

    // 发行或运行时启用了压缩时会生效
    config.optimization.minimizer('terser').tap(args => {
      const compress = args[0].terserOptions.compress;
      // 非 App 平台移除 console 代码(包含所有 console 方法，如 log,debug,info...)
      compress.drop_console = isBuild && isProduction; // 移除
      compress.pure_funcs =
        isBuild && isProduction
          ? []
          : [
              '__f__', // App 平台 vue 移除日志代码
              'console.debug', // 可移除指定的 console 方法
              'console.log' // 可移除指定的 console 方法
            ];
      return args;
    });
  }
};
